var baseUrl = "/m";
var defaultDaysPerWeek = 5;//默认每周的上课天数
var defaultAmLessonCount = 4;//默认每天上午的课时数
var defaultPmLessonCount = 3;//默认每天下午的课时数
var defaultEveLessonCount = 0;//默认每天晚上的课时数
var isDeleted = false;//是否在规则列表中删除单个规则
var maxLesson = 7;
var item = $("#divBody");
$(function () {
    if (getQueryString("action") != null) {
        $("#li5 a:first").click();
    } else {
        setTaskStep("baseInfo");
        setTaskRuleStep("li0");
    }

    $("button[name=btnUp]").click(function () {
        $("#myModal").modal({
            keyboard: true,
            backdrop: true,
            show: true
        });
    })

    $('#myModal').on('show.bs.modal', function () {
        showInfo();
    })
    $('#myModal').on('shown.bs.modal', function () {
        createUploader();
    })


    $('#myModal').on('hidden.bs.modal', function () {
        $("#uploadInfo").css("display", "none");
    })

    searchBaseInfo();

    //searchPublicCourse();
    //获取课表结构
    getTimeTableStructure();


});


function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

// 获取基础信息
function searchBaseInfo() {
    jQuery.ajax({
        url: "/m/baseInfo/getBaseInfo".addTimestamp(),
        data: {"taskId": taskId},
        dataType: "json",
        type: "GET",
        success: function (ret) {
            if (ret.data != null && ret.data.length > 1) {
                uploadTeacherSuccess(ret.data)
                setVisible(1)
                bindHover(1);
                bindHover(2);
                $("li.export").show();
                $("#input3").val(1);
            }
            else {
                $("li.export").hide();
                setHidden(1);
                setVisibleInfo(1)
                $("#input3").val(0);
            }
        }
    })
}
function searchRoom() {
    jQuery.ajax({
        url: "/m/classroom/json/list".addTimestamp(),
        data: {"taskId": taskId},
        dataType: "json",
        type: "GET",
        success: function (ret) {
            var obj = $("#divSpecialClassInfo");
            obj.empty();
            var htmlStr = "";
            if(ret!=null&&ret!=""&&ret!=undefined&&ret.length>1){
                htmlStr+="<table class='table'>";
                for(var i=0;i<ret.length;i++){
                    if(i==0){
                        htmlStr+="<thead>"
                        htmlStr+="<tr>"
                        for(var j=0;j<ret[i].length;j++){
                            htmlStr+="<th>"+ret[i][j]+"</th>";
                        }
                        htmlStr+="</tr>"
                        htmlStr+="</thead>"
                        continue;
                    }
                    else if(i==1){
                        htmlStr+="<tbody>"
                    }
                    htmlStr+="<tr>"
                    for(var j=0;j<ret[i].length;j++){
                        htmlStr+="<td>"+ret[i][j]+"</td>";
                    }
                    htmlStr+="</tr>"
                }
                htmlStr+="</tbody>"
                htmlStr+="</table>";
                obj.append(htmlStr);
                $("#showSpecialClassRoomBtn").show();
                $("#downSpecialClassRoomBtn").show();

            }
            //setHidden(3);
            //setVisibleInfo(3)
            /*
            if (ret.length > 1) {
                uploadClassRoomSuccess(ret)
                setVisible(3)
                bindHover(3);
                $("li.classroom").show();

            }
            else {
                $("li.classroom").hide();
                setHidden(3);
                setVisibleInfo(3)
            }*/
        }
    })
}

function searchClassInfoRoom() {
    jQuery.ajax({
        url: "/m/classroom/json/listForClass".addTimestamp(),
        data: {"taskId": taskId},
        dataType: "json",
        type: "GET",
        success: function (ret) {
            var obj = $("#divClassRoomInfo");
            obj.empty();
            var htmlStr = "";
            if(ret!=null&&ret!=""&&ret!=undefined&&ret.length>1){
                htmlStr+="<table class='table'>";
                for(var i=0;i<ret.length;i++){
                    if(i==0){
                        htmlStr+="<thead>"
                        htmlStr+="<tr>"
                        for(var j=0;j<ret[i].length;j++){
                            htmlStr+="<th>"+ret[i][j]+"</th>";
                        }
                        htmlStr+="</tr>"
                        htmlStr+="</thead>"
                        continue;
                    }
                    else if(i==1){
                        htmlStr+="<tbody>"
                    }
                    htmlStr+="<tr>"
                    for(var j=0;j<ret[i].length;j++){
                        htmlStr+="<td>"+ret[i][j]+"</td>";
                    }
                    htmlStr+="</tr>"
                }
                htmlStr+="</tbody>"
                htmlStr+="</table>";
                obj.append(htmlStr);
                $("#showClassRoomBtn").show();
                $("#downClassRoomBtn").show();
            }
        }
    })
}

function classRoomNonShow() {
    if($("#input3").val()=="1"){
        $("#p3").empty();
        var htmlStr = "<table id='table3' name='tblInfo3' class='tableinfo' style='width:500px;'>";
        htmlStr+="<tr>";
        htmlStr+="<td>班级教室</td>"
        htmlStr+="<td colspan='2'><div style='text-align: left'>若课程表中无教室要求，则可不上传教室信息。<br/>请下载<a href='javascript:void(0)' onclick='return downloadClassRoomTemplate();'>班级教室模板</a>，正确填写后上传</div></td>"
        htmlStr+="</tr>"
        htmlStr+="<tr>";
        htmlStr+="<td></td>"
        htmlStr+="<td><button class='btn btn-primary btn-sm' id='showClassRoomBtn' style='display: none;'>查看班级教室信息</button></td>"
        htmlStr+="<td><button class='btn btn-primary btn-sm' id='uploadClassRoomBtn'>上传班级教室</button></td>"
        htmlStr+="<td><button class='btn btn-primary btn-sm' id='downClassRoomBtn' style='display: none' onclick='downloadClassRoomTemplate()'>下载班级教室信息</button></td>"
        htmlStr+="</tr>";
        htmlStr+="<tr>";
        htmlStr+="<td>专业教室</td>"
        htmlStr+="<td colspan='2'><div style='text-align: left'>若无专业教室要求，则可不上传专业教室信息。<br/>请下载<a href='javascript:void(0)' onclick='return downloadSpecialClassRoomTemplate();'>专业教室模板</a>，正确填写后上传</div></td>"
        htmlStr+="</tr>"
        htmlStr+="<tr>";
        htmlStr+="<td></td>"
        htmlStr+="<td><button class='btn btn-primary btn-sm' id='showSpecialClassRoomBtn' style='display: none;'>查看专业教室信息</button></td>"
        htmlStr+="<td><button class='btn btn-primary btn-sm' id='uploadSpecialClassRoomBtn'>上传专业教室</button></td>"
        htmlStr+="<td><button class='btn btn-primary btn-sm' id='downSpecialClassRoomBtn' style='display: none' onclick='downloadSpecialClassRoom()'>下载专业教室信息</button></td>"
        htmlStr+="</tr>";
        htmlStr+="</table>";
        $("#p3").append(htmlStr);
        $("#table3").css("display","table");

        $("#uploadClassRoomBtn").click(function () {
            fileType="uploadClassInfoClassRoom";
            title = titleArray[10];
            $("#myModal").modal({
                keyboard: true,
                backdrop: true,
                show: true
            });

        })
        $("#uploadSpecialClassRoomBtn").click(function () {
            fileType="uploadClassRoom";
            title = titleArray[2];
            $("#myModal").modal({
                keyboard: true,
                backdrop: true,
                show: true
            });

        })

        $("#showSpecialClassRoomBtn").click(function () {
            $("#spcialClassRoomInfo").modal({
                show: true
            });

        })

        $("#showClassRoomBtn").click(function () {
            $("#clssInfoClassRoomInfo").modal({
                show: true
            });

        })


        searchRoom();
        searchClassInfoRoom();
    }else{
        setVisibleInfo(3);
    }
}

function downloadSpecialClassRoomTemplate() {
    downloadSpecialClassRoom();
}

function restart() {
    if (confirm("确认要重新开始吗？")) {
        jQuery.ajax({
            url: "/m/baseInfo/restart".addTimestamp(),
            data: {"taskId": taskId},
            dataType: "json",
            type: "GET",
            success: function (ret) {
                window.location.reload();
            }
        })
    }
}
function searchPublicCourse() {
    jQuery.ajax({
        url: "/m/course/getPublicCourse".addTimestamp(),
        data: {"taskId": taskId},
        dataType: "json",
        type: "GET",
        success: function (ret) {
            if (ret.data.length > 1) {
                uploadTeachingGroupSuccess(ret.data)
                setVisible(4)
                bindHover(4);
            }
            else {
                setHidden(4);
                setVisibleInfo(4)
            }
        }
    })
}
function switchTab(sender) {
    $("#ulTab").find("a").removeClass("colorful");
    $link = $(sender);
    $link.addClass("colorful");
    fileType = fileTypeArray[$link.attr("tabindex")];
    title = titleArray[$link.attr("tabindex")];
    img = imgArray[$link.attr("tabindex")];
    template = templateArray[$link.attr("tabindex")];
    promptInfo = promptInfoArray[$link.attr("tabindex")];
    classRoomNonShow();
}

/**
 * 上传成功
 * @param result
 */
function uploadTeacherSuccess(result) {
    var htmlClass =  new Array();
    // var htmlTeacher = new Array();
    htmlClass.push("<table class='info' id='tblClass'>"); //课时
    // htmlTeacher.push("<table class='info' id='tblTeacher'>"); //上课老师
    for (i = 0; i < result.length; i++) {

        htmlClass.push("<tr>");
        // htmlTeacher.push("<tr>");
        var total = 0;
        var strClass = "";
        var strTeacher = "";
        for (j = 0; j < result[i].length; j++) {
            var val = result[i][j] == null ? "" : result[i][j];
            if (j < 2) { //第一列和第二列全部填充
                htmlClass.push("<td>" + val + "</td>");
                // htmlTeacher.push("<td>" + val + "</td>");
            }
            else {//从第三列开始分开填充课时和老师表。
                if (j % 2 == 0) {
                    var teacherName = "";
                    if(i>0) {
                        teacherName = result[i][j + 1] == null ? "" : "<br>"+result[i][j + 1]+"";
                    }
                    strClass += "<td>" + val + teacherName+"</td>";
                    total += getLessonTimes(val);
                } else {
                    strTeacher += "<td>" + val + "</td>";
                }
            }
        }
        if (i== 0 ){
            htmlClass.push("<td>总课时数</td>");
        }else{
            htmlClass.push("<td>" + total + "</td>");
        }
        htmlClass.push(strClass +"</tr>");
        // htmlTeacher.push(strTeacher +"</tr>");
    }
    htmlClass.push("</table>");
    // htmlTeacher.push("</table>");
    $("#p1").html(htmlClass.join(""));
    // $("#p2").html(htmlTeacher.join(""));
    // setHiddenInfo(1);
}
/**
 * parse the lessonTime String
 * @param val
 */
function getLessonTimes(val){
    val = trim(val);
    if(val=="" || isNaN(val)){
        if(val.indexOf("+") >= 0){
            var strs = val.split("+");
            return parseInt(strs[0]) + parseInt(strs[1])*2;
        }
        return 0;
    }
    return parseInt(val);
}
function uploadClassRoomSuccess(data) {
    uploadSuccess(data, $("#p3"));
    setHiddenInfo(3)
}
function uploadTeachingGroupSuccess(data) {
    uploadSuccess(data, $("#p4"));
    setHiddenInfo(4)
}
function uploadSuccess(result, element) {
    var strHtml = "<table class='info'>";
    for (i = 0; i < result.length; i++) {
        strHtml += "<tr>";
        for (j = 0; j < result[i].length; j++) {
            strHtml += "<td>" + result[i][j] + "</td>";
        }
        strHtml += "</tr>"
    }
    strHtml += "</table>";
    element.html(strHtml);
}
/*弹出层相关*/
$('#myModal').on('show.bs.modal', function (e) {
    $(this).find('.modal-dialog').css({
        'margin-top': function () {
            var modalHeight = 445;// $('#myModal').find(".modal-dialog").height();
            return ($(window).height() - modalHeight ) / 2;
        }
    });
});
//$(function () {
//    $("a[name=btnUp]").click(function () {
//        $("#myModal").modal({
//            keyboard: true,
//            backdrop: true,
//            show: true
//        });
//    })
//    $('#myModal').on('show.bs.modal', function () {
//        showInfo();
//    })
//    $('#myModal').on('shown.bs.modal', function () {
//        createUploader();
//    })
//
//    //$('#myModal').on('show.bs.modal', function () {
//    //    $(this).css("width", "500px")
//    //    $(this).css("margin-left", ($(window).width() / 2 - 300) + "px")
//    //});
//
//
//    $('#myModal').on('hidden.bs.modal', function () {
//        $("#uploadInfo").css("display", "none");
//    })
//})

function setVisible(value) {
    $("table[name='tblImpt" + value + "']").css("display", "inline-table");
}
function setHidden(value) {
    $("table[name='tblImpt" + value + "']").css("display", "none");
}
function setHiddenInfo(value) {
    $("table[name='tblInfo" + value + "']").css("display", "none");
}
function setVisibleInfo(value) {
    $("table[name='tblInfo" + value + "']").css("display", "inline-table");
}

function bindHover(i) {
    switch (i) {
        case 1:
            initHover($("#p1 table tr", false).not("#p1 table tr:first"));
            break;
        case 2:
            initHover($("#p2 table tr", false).not("#p2 table tr:first"));
            break;
        case 3:
            initHover($("#p3 table tr", false).not("#p3 table tr:first"));
            break;
        case 4:
            initHover($("#p4 table tr", false).not("#p4 table tr:first"));
            break;
    }
}

String.prototype.addTimestamp = function () {
    return this + "?t=" + (new Date().getTime()).toString();
}

/*从后台获取课表结构*/
function getTimeTableStructure() {
    jQuery.ajax({
        type: "GET",
        url: "/m/rule/getTimeTableStructure?taskId=" + taskId,
        async: false,
        cache: false,
        success: function (msg) {
            var message = JSON.parse(msg);
            var retData = message.data;
            if (retData != null) {
                //isTimeTableOk = true;
                defaultDaysPerWeek = retData.daysPerWeek;
                defaultAmLessonCount = retData.amLessonCount;
                defaultPmLessonCount = retData.pmLessonCount;
                defaultEveLessonCount = retData.eveLessonCount;
            }
            /*初始化课表结构下拉框*/
            initTableStructureSlt();

            // 如果没有设置过课表结构，弹出设置
            if (hasSetTimetableStructure == 0) {
                showTimeTableModal();

                // 更新已设置
                setHasSetTimetableStructure();
            }
        }
    });
}

///*初始化课表结构下拉框*/
function initTableStructureSlt() {
    var daysPerWeekHtml = new Array();
    for (var i = 1; i <= 7; i++) {
        if (defaultDaysPerWeek == i) {
            daysPerWeekHtml.push("<option selected value=" + i + ">" + i + "天</option>");
        } else {
            daysPerWeekHtml.push("<option value=" + i + ">" + i + "天</option>");
        }
    }
    $("#daysPerWeek").html(daysPerWeekHtml.join(""));
    var defaultAmLessonHtml = new Array();
    for (var i = 0; i <= maxLesson; i++) {
        if (defaultAmLessonCount == i) {
            defaultAmLessonHtml.push("<option selected value=" + i + ">" + i + "节</option>");
        } else {
            defaultAmLessonHtml.push("<option value=" + i + ">" + i + "节</option>");
        }
    }
    $("#amLessonCount").html(defaultAmLessonHtml.join(""));
    var defaultPmLessonHtml = new Array();
    for (var i = 0; i <= maxLesson; i++) {
        if (defaultPmLessonCount == i) {
            defaultPmLessonHtml.push("<option selected value=" + i + ">" + i + "节</option>");
        } else {
            defaultPmLessonHtml.push("<option value=" + i + ">" + i + "节</option>");
        }
    }
    $("#pmLessonCount").html(defaultPmLessonHtml.join(""));
    var defaultEveLessonHtml = new Array();
    for (var i = 0; i <= maxLesson; i++) {
        if (defaultEveLessonCount == i) {
            defaultEveLessonHtml.push("<option selected value=" + i + ">" + i + "节</option>");
        } else {
            defaultEveLessonHtml.push("<option value=" + i + ">" + i + "节</option>");
        }
    }
    $("#eveLessonCount").html(defaultEveLessonHtml.join(""));
}

function updateTimeTableStructure() {
    if (hasCoursePlan == "0") {
        saveTimeTableStructure();
    } else if (confirm("修改时间安排会导致已排完的课表不可用且无法恢复！确定要改变么？")) {
        jQuery.ajax({
            url: "/m/task/disable",
            type: "POST",
            data: {"taskId": taskId},
            success: function (ret) {
                if (parseInt(ret) > 0) {
                    saveTimeTableStructure();
                } else {
                    alert("操作失败!请重试或者联系管理员!");
                }
            }
        })
    }
}

/*动态构建课表结构样式*/
function saveTimeTableStructure() {
    //task-coursePlan
    var daysPerWeek = parseInt($("#daysPerWeek").val());
    var amLessonCount = parseInt($("#amLessonCount").val());
    var pmLessonCount = parseInt($("#pmLessonCount").val());
    var eveLessonCount = parseInt($("#eveLessonCount").val());

    var ret = setTimeTableStructure(daysPerWeek, amLessonCount, pmLessonCount, eveLessonCount);
    if (ret == true) {
        reloadPage();
    }
}

/*将课表结构数据写入后台，同时清除之前设置的所有规则*/
function setTimeTableStructure(daysPerWeek, amLessonCount, pmLessonCount, eveLessonCount) {
    var ret = false;
    var jsonArray = {
        "daysPerWeek": daysPerWeek, "amLessonCount": amLessonCount,
        "pmLessonCount": pmLessonCount, "eveLessonCount": eveLessonCount,
        "DoubleLesson": 0
    };
    var postData = {
        "taskId": taskId,
        "json": JSON.stringify(jsonArray)
    };
    jQuery.ajax({
        type: "POST",
        url: "/m/rule/setTimeTableStructure",
        cache: false,
        async: false,
        data: postData,
        success: function (msg) {
            var message = JSON.parse(msg);
            if (message != null) {
                ret = message;
            }
        }
    });
    return ret;
}

function showTimeTableModal(sender) {
    $("#ulTab").find("a").removeClass("colorful");
    $link = $(sender);
    $link.addClass("colorful");
    $('#myModalJieCi').modal('show');
}

$('#myModalJieCi').on('show.bs.modal', function (e) {
    $(this).find('.modal-dialog').css({
        'margin-top': function () {
            var modalHeight = 445;// $('#myModal').find(".modal-dialog").height();
            return ($(window).height() - modalHeight ) / 2;
        }
    });
});

function setHasSetTimetableStructure() {
    jQuery.ajax({
        type: "POST",
        url: "/m/rule/setHasSetTimetableStructure",
        data: {"taskId": taskId},
        success: function (msg) {
        }
    });
}


function reloadPage() {
    location.reload();
    //window.location.href = "/m/rule/unScheduleRule?taskId=" + taskId;
}

function downloadBaseInfo() {
    //window.location.href = "/m/baseInfo/downloadBaseInfo?taskId=" + taskId +"&type=" + type;
    window.location.href = "/m/teachingplan/download?taskId=" + taskId;
}
function downloadCourseInfo() {
    window.location.href = "/m/courseplan/downloadCoursePlanOfAll?taskId=" + taskId+"&type=0"+"&style="+1;
}
function downloadSpecialClassRoom() {
    window.location.href = "/m/classroom/download?taskId=" + taskId;
}

function downloadClassRoomTemplate() {
    window.location.href="/m/classroom/downloadGradeClassRoom?taskId=" + taskId;
}